﻿using System.Text;
using System.Xml;
using System.Collections.Generic;

namespace NJabber.Stream.Elements
{
    public abstract class XmppStreamElement
    {
        private Dictionary<string, object> attributes;
        private XmlWriterSettings writerSettings;
        private XmlNamespace elementNamespace;
        private string name;

        protected XmppStreamElement(string name) : this(name, "")
        {
        }

        protected XmppStreamElement(string name, string namespaceUri) : this(name, "", namespaceUri)
        {
        }

        protected XmppStreamElement(string name, string namespaceName, string namespaceUri)
        {
            this.name = name;
            elementNamespace = new XmlNamespace(namespaceName, namespaceUri);
            attributes = new Dictionary<string, object>();
            writerSettings = new XmlWriterSettings();
            writerSettings.OmitXmlDeclaration = true;
        }

        public string Name
        {
            get { return name; }
        }

        public XmlNamespace Namespace
        {
            get { return elementNamespace; }
        }
        
        protected XmlWriterSettings WriterSettings
        {
            get { return writerSettings; }
        }

        protected virtual void OnBeforeWrite()
        { }

        protected XmlWriter CreateWriter(StringBuilder builder)
        {
            return XmlWriter.Create(builder, WriterSettings);
        }

        #region Attribute methods

        protected bool HasAttribute(string namespaceName, string name, string namespaceUri)
        {
            string id = GetAttributeId(namespaceName, name, namespaceUri);
            return attributes.ContainsKey(id);
        }

        protected object GetAttributeValue(string name)
        {
            return GetAttributeValue("", name, "");
        }

        protected object GetAttributeValue(string namespaceName, string name, string namespaceUri)
        {
            string id = GetAttributeId(namespaceName, name, namespaceUri);
            if (!attributes.ContainsKey(id)) return null;
            return attributes[id];
        }

        protected void SetAttributeValue(string name, object value)
        {
            SetAttributeValue("", name, "", value);
        }

        protected void SetAttributeValue(string namespaceName, string name, string namespaceUri, object value)
        {
            string id = GetAttributeId(namespaceName, name, namespaceUri);
            attributes[id] = value;
        }

        private string GetAttributeId(string namespaceName, string name, string namespaceUri)
        {
            return string.Format("{0}:{1}:{2}", namespaceName, name, namespaceUri);
        }

        #endregion

        #region Write methods

        public void Write(StringBuilder stringBuilder)
        {
            XmlWriter writer = CreateWriter(stringBuilder);
            Write(writer);
            writer.Close();
        }

        public virtual void Write(XmlWriter writer)
        {
            OnBeforeWrite();
            WriteStartElement(writer);
            WriteAttributes(writer);
            WritePayload(writer);
            WriteEndElement(writer);
        }

        protected virtual void WriteStartElement(XmlWriter writer)
        {
            writer.WriteStartElement(Namespace.Name, Name, Namespace.Uri);
        }

        protected virtual void WriteAttributes(XmlWriter writer)
        {
            if (attributes == null || attributes.Count == 0) return;
            foreach (string attributeId in attributes.Keys)
            {
                if (attributes[attributeId] == null) continue;
                string value = attributes[attributeId].ToString();
                if (value == "") continue;
                WriteAttribute(writer, attributeId, value);
            }
        }

        private static void WriteAttribute(XmlWriter writer, string attributeId, string value)
        {
            string[] attrParts = attributeId.Split(':');
            writer.WriteAttributeString(attrParts[0], attrParts[1], attrParts[2], value);
        }

        protected virtual void WriteEndElement(XmlWriter writer)
        {
            writer.WriteEndElement();
        }

        protected virtual void WritePayload(XmlWriter writer)
        {
        }

        #endregion

        public override bool Equals(object obj)
        {
            if (obj == null) return false;
            if (!(obj is XmppStreamElement)) return false;

            return Equals((XmppStreamElement) obj);
        }

        public bool Equals(XmppStreamElement element)
        {
            if (element == null) return false;
            return Name.Equals(element.Name) && Namespace.Equals(element.Namespace) && AreAttributesEquals(this, element);
        }

        private bool AreAttributesEquals(XmppStreamElement element1, XmppStreamElement element2)
        {
            foreach (string attributeId in element1.attributes.Keys)
            {
                if (!element2.attributes.ContainsKey(attributeId)) return false;
                if (!AreValuesEquals(attributes[attributeId], element2.attributes[attributeId])) return false;
            }
            return true;
        }

        protected bool AreValuesEquals(object val1, object val2)
        {
            if (val1 == null && val2 == null) return true;
            if (val1 == null) return false;
            return val1.Equals(val2);
        }

        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            Write(sb);
            return sb.ToString();
        }
    }
}
